package com.atguigu.servlet;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.atguigu.beans.User;
import com.atguigu.dao.UserDao;
import com.atguigu.dao.impl.UserDaoImpl;

/**
 * 处理用户登录的Servlet
 */
public class LoginServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
		//1.获取用户名和密码
		String username = request.getParameter("username");
		String password = request.getParameter("password");
		//2.创建UserDao对象
		UserDao userDao = new UserDaoImpl();
		//3.调用UserDao中验证用户名和密码的方法
		User user = userDao.checkUsernameAndPassword(username, password);
		if(user != null) {
			//证明用户名和密码正确，将用户信息保存在Session域中
			HttpSession session = request.getSession();
			session.setAttribute("user", user);
			//重定向到登录成功页面
			response.sendRedirect(request.getContextPath()+"/GetUsersServlet");
			System.out.println(request.getContextPath());
		}else {
			//用户名或密码不正确，设置一个提示信息并放到request域中
			request.setAttribute("msg", "用户名或密码不正确！");
			//转发到登录页面
			RequestDispatcher requestDispatcher = request.getRequestDispatcher("/pages/login.jsp");
			requestDispatcher.forward(request, response);
		}
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doGet(request, response);
	}

}
